<template>
  <div style="height: 100%">
    <div class="formCard-content">
      <Card :bordered="false" :dis-hover="true" :shadow="false" class="formCard">
        <div class="searchArea">
          <Form ref="queryForm" :model="queryForm" :label-width="80">
            <Row :gutter="40">
              <Col span="6" style="margin-bottom: 12px">
                <FormItem label="模块名称" prop="formName" style="width: 100%">
                  <Input type="text" :maxlength="100" v-model.trim="queryForm.formName" placeholder="请输入模块名称"
                         style="width: 100%"/>
                </FormItem>
              </Col>
              <Col span="6" style="margin-bottom: 12px">
                <FormItem label="数据表" prop="formTable" style="width: 100%">
                  <Input type="text" :maxlength="100" v-model.trim="queryForm.formTable" placeholder="请输入模块数据表"
                         style="width: 100%"/>
                </FormItem>
              </Col>
              <Col span="6" style="margin-bottom: 12px">
                <FormItem label="模块类型" prop="formType" style="width: 100%">
                  <Select v-model.trim="queryForm.formType" placeholder="请选择">
                    <Option value="0">单表</Option>
                    <Option value="1">多表</Option>
                    <Option value="3">流程表</Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="24" style="text-align: right; margin-top: 12px">
                <FormItem :label-width="0">
                  <Button type="primary" @click="queryList(true)" style="margin-right: 8px">查询</Button>
                  <Button type="default" @click="handleReset('queryForm')">重置</Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </Card>
      <Card :bordered="false" :dis-hover="true" :shadow="false" class="formCard">
        <div class="tableBtn">
          <Button @click="okFlag = 'add';openAdd()" type="primary" style="margin-right: 10px;" icon="md-add">新建模块
          </Button>
          <Button icon="ios-trash-outline" type="error" @click="handleDeleteMultiple()" style="margin-left: 5px">删除
          </Button>
        </div>
        <Table :columns="columns" :data="data" @on-selection-change="rowSelected($event)" style="">
          <template slot-scope="{ row }" slot="typeAction">
            <!--            <span  v-if="row.formType=='0'" style="font-size:15px;font-weight:bold;color: #2d8cf0" >单表</span>-->
            <!--            <span  v-else style="font-size:15px;font-weight:bold;color: #47cb89" >多表</span>-->
            <Button v-if="row.formType=='0'" type="success" size="small" style="margin-right: 5px; color: #f1f5f8">单表
            </Button>
            <Button v-else-if="row.formType=='3'" type="warning" size="small" style="margin-right: 5px; color: #f1f5f8">
              流程表
            </Button>
            <Button v-else type="primary" size="small" style="margin-right: 5px; color: #f1f5f8">多表</Button>
          </template>
          <template slot-scope="{ row, index }" slot="action">
            <Button type="text" size="small" style="margin-right: 5px; color: #0056b5"
                    @click="okFlag = 'update';openAdd(row, index)">编辑
            </Button>
            <Button v-if="row.formType=='0'" type="text" size="small" style="margin-right: 5px; color: #0056b5"
                    @click="handleEdit(row, index)">
              单表设计
            </Button>
            <Button v-if="row.formType=='1'" type="text" size="small" style="margin-right: 5px; color: #0056b5"
                    @click="handleEdit(row, index)">
              主表设计
            </Button>
            <!-- <Tooltip v-if="row.formType=='1'" content="请先完成主表设计" placement="top-start"> -->
            <Button v-if="row.formType=='1'" :disabled="row.formTable==null" :class="row.formTable==null?'':'normal'"
                    type="text" size="small" @click="handleTableChild(row, index)">
              子表设计
            </Button>
            <!-- </Tooltip> -->
            <Button v-if="row.formType=='3'" type="text" size="small" style="margin-right: 5px; color: #0056b5"
                    @click="handleEdit(row, index)">
              流程表设计
            </Button>
            <Button type="text" size="small" style="margin-right: 5px; color: #0056b5" @click="remove(row, index)">
              删除
            </Button>
          </template>
        </Table>
        <Page :total="pageData.total" :page-size="pageData.size" :current="pageData.page" show-elevator show-sizer
              show-total @on-page-size-change="changePage($event, 'size')" @on-change="changePage($event, 'page')"
              style="margin-top: 20px"/>
      </Card>
    </div>
    <Modal v-model="modal1" :title="modalTitle">
      <Form ref="moduleRules" :model="detail" :rules="fieldRuleValidate" :label-width="80" style="margin-top: 20px">
        <FormItem label="模块名称" prop="formName">
          <Input type="text" :maxlength="100" v-model="detail.formName"
                 placeholder="请输入模块名称"></Input>
        </FormItem>
        <FormItem label="模块类型" prop="formType">
          <Select v-model="detail.formType" placeholder="请选择" :disabled="typeDisabled">
            <Option v-for="item in formTypeOption" :value="item.value.toLocaleString()"
                    :key="item.value.toLocaleString()">{{ item.label }}
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="save" style="width: 80px"
        >确定
        </Button
        >
        <Button type="default" @click="cancel" style="width: 80px"
        >取消
        </Button
        >
      </div>
    </Modal>
    <config-page ref="configRef" :formType="formType" formId1=''/>
  </div>
</template>

<script>
import ConfigPage from '@/views/lowcode/customize/components/configPage'

export default {
  name: 'customizeVformManager',
  components: { ConfigPage },
  data () {
    let validateFormName = (rule, value, callback) => {
      if (value.length > 15) {
        callback(new Error('模块名长度小于等于15'))
      } else if (value.length <= 15) {
        const [url, httpConfig] = [
          '/api/lowcode/customize/getCscpCustomizeVformByName',
          {
            params: { formName: value }
          }
        ]
        this.$http
          .get(url, httpConfig)
          .then((response) => {
            console.log('response.data.length > 0', response.data.length > 0)
            if (response.data.length > 0) {
              callback(new Error('模块名已重复'))
            } else {
              callback()
            }
          })
          .catch(() => {
            callback(new Error('异步校验出错！'))
          })
      }
    }
    return {
      fieldRuleValidate: {
        formName: [
          { required: true, message: '字段名称不能为空！！', trigger: 'blur' },
          { required: true, validator: validateFormName, trigger: 'blur' }

        ]
      },
      formTypeOption: [
        { value: '0', label: '单表' },
        { value: '1', label: '多表' },
        { value: '3', label: '流程表' }
      ],
      isShowTip: false,
      modal1: false,
      selectedArr: [],
      queryForm: {},
      formId: null,
      formType: '0',
      pageData: {
        total: 0,
        size: 10,
        page: 1
      },
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          type: 'index',
          align: 'center',
          title: '序号',
          width: 70
        },
        {
          title: '模块名称',
          key: 'formName',
          align: 'center'
        },
        {
          title: '模块数据表',
          key: 'formTable',
          align: 'center'
        },
        {
          title: '模块类型',
          key: 'formType',
          align: 'center',
          slot: 'typeAction'
        },
        {
          title: '创建时间',
          key: 'createdTime',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          width: 300,
          align: 'center'
        }
      ],
      data: [],
      detail: {},
      okFlag: 'add',
      modalValid: true,
      ruleValidate: {},
      modalTitle: '',
      typeDisabled: false,
      tagetRow: '',
      moduleName: ''
    }
  },
  mounted () {
    this.queryList()
    this.moduleName = this.$route.query.key
    this.$route.query.key ? this.copyQueryList() : ''
  },
  methods: {
    handleTableChild (row) {
      this.$byStoreSet('mainForm', row)
      this.$router.push({
        name: 'sub-lowcode-programming'
      })
    },
    // 表单名称是否重复 验证
    judgeFormNameRepeat () {
      let params = { formName: this.detail.formName }
      this.$http.get('/api/lowcode/customize/getCscpCustomizeVformByName', { params }).then(res => {
        res.data.length ? this.isShowTip = true : this.isShowTip = false
      })
    },
    openAdd (row, index) {
      this.isShowTip = false
      this.modal1 = true
      this.detail = { formType: 0 }
      if (this.okFlag == 'update') {
        this.modalTitle = '编辑模块'
        this.$http
          .get('/api/lowcode/customize/cscpCustomizeVforms/' + row.formId)
          .then((res) => {
            this.detail = res.data
            this.typeDisabled = true
          })
          .catch(() => {
            this.$Message.error('行数据查询失败')
          })
      } else {
        this.modalTitle = '新增模块'
        this.typeDisabled = false
      }
    },
    save () {
      this.$refs.moduleRules.validate((valid) => {
        if (valid) {
          if (this.isShowTip) return false
          if (this.okFlag === 'update') {
            this.$http
              .put('/api/lowcode/customize/cscpCustomizeVforms', this.detail)
              .then((res) => {
                this.$Message.success('修改成功')
                // this.modal1 = false
                this.queryList()
                this.$refs['moduleRules'].resetFields()
              })
              .catch(() => {
                this.$Message.error('修改失败')
              })
            this.modal1 = false
          } else if (this.okFlag === 'add') {
            if (this.detail.formName) {
              let copyDetail = JSON.parse(JSON.stringify(this.detail))
              this.$http
                .post('/api/lowcode/customize/cscpCustomizeVforms', copyDetail)
                .then((res) => {
                  this.$Message.success('新增成功')

                  this.queryList()
                })
                .catch(() => {
                  this.$Message.error('新增失败')
                })
              this.modal1 = false
            }
          }
        } else {
          this.modal1 = true
          this.$Message.error({
            background: true,
            content: '检验数据失败！'
          })
        }
      })
    },
    changePage (e, type) {
      if (type === 'size') {
        this.pageData.size = e
      } else if (type === 'page') {
        this.pageData.page = e
      }
      this.queryList()
    },
    handleAdd () {
      this.detail = {}
      this.okFlag = 'add'
    },
    handleEdit (row, index) {
      console.log(row)
      window.localStorage.setItem('widget__list__backup', '')
      window.localStorage.setItem('form__config__backup', '')
      // 页面状态记录
      let pageJson = JSON.parse(row.formJson ? row.formJson : null)
      if (pageJson) {
        window.localStorage.setItem('widget__list__backup', JSON.stringify(pageJson.widgetList))
        window.localStorage.setItem('form__config__backup', JSON.stringify(pageJson.formConfig))
      }
      // 将行数据传递给子组件
      this.$refs['moduleRules'].resetFields()
      this.formId = row.formId
      this.$refs.configRef.currentStep = 0
      this.$refs.configRef.configModal = true
      this.$http
        .get('/api/lowcode/customize/cscpCustomizeVforms/' + row.formId)
        .then((res) => {
          this.detail = res.data
          this.formType = res.data.formType
          this.$refs.configRef.tableName = res.data.formTable
          this.$refs.configRef.tableDesc = res.data.tableDesc
          this.$refs.configRef.formId = res.data.formId
          this.$refs.configRef.formJson = res.data.formJson
          this.okFlag = 'update'
          if (res.data.formTable) {
            this.$refs.configRef.isDisable = true
            this.$refs.configRef.$refs.formDbRef.getColumns(res.data.formTable)
            this.$refs.configRef.$refs.formDbRef.tableName = res.data.formTable
            this.$refs.configRef.$refs.formDbRef.tableDesc = res.data.tableDesc
          } else {
            this.$refs.configRef.isDisable = false
          }
        })
        .catch(() => {
          this.$Message.error('行数据查询失败')
        })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
      this.selectedArr = []
      this.queryList()
    },
    rowSelected (e) {
      this.selectedArr = e
    },
    remove (row, index) {
      this.$Modal.confirm({
        title: '警告',
        content: '<p>确定删除这条数据？</p>',
        onOk: () => {
          this.$http
            .delete('/api/lowcode/customize/cscpCustomizeVforms/' + row.formId)
            .then((res) => {
              if (res.data.msg) {
                this.$Message.error(res.data.msg)
                return
              } else {
                this.$Message.success('删除成功')
              }
              this.queryList()
            })
            .catch(() => {
              this.$Message.error('删除失败')
            })
        },
        onCancel: () => {
        }
      })
    },
    ok (type) {
      this.$delete(this.detail, '')
      this.$delete(this.detail, '_rowKey')
      let copyDetail = JSON.parse(JSON.stringify(this.detail))
      if (this.detail.createdTime) {
        copyDetail.createdTime = this.$moment(
          new Date(this.detail.createdTime)
        ).format('yyyy-MM-DD HH:mm:ss')
      }

      this.$refs['detail'].validate((valid) => {
        if (valid) {
          if (type === 'update') {
            this.$http
              .put('/api/customizeVforms', copyDetail)
              .then((res) => {
                this.$Message.success('修改成功')
                this.queryList()
                this.$refs['moduleRules'].resetFields()
              })
              .catch(() => {
                this.$Message.error('修改失败')
              })
          } else if (type === 'add') {
            this.$http
              .post('/api/customizeVforms', copyDetail)
              .then((res) => {
                this.$Message.success('新增成功')
                this.$refs['queryForm'].resetFields()
                this.queryList()
                this.$refs['moduleRules'].resetFields()
              })
              .catch(() => {
                this.$Message.error('新增失败')
              })
          }
        } else {
          // this.modal = true
        }
      })
    },
    queryList (flag) {
      if (flag) {
        this.pageData.page = 1
      }
      let obj = {}
      obj['formName'] = this.queryForm['formName'] ? this.queryForm['formName'] : null
      obj['formTable'] = this.queryForm['formTable'] ? this.queryForm['formTable'] : null
      if (this.queryForm['formType']) {
        obj['formType'] = this.queryForm['formType']
      }

      let params = Object.assign(obj, {
        page: this.pageData.page - 1,
        size: this.pageData.size
      })
      this.$http
        .get('/api/lowcode/customize/cscpCustomizeVforms/getList', {
          params: params
        })
        .then((res) => {
          this.data = res.data.data
          this.pageData.total = res.data.recordsTotal
        })
        .catch(() => {
          this.$Message.error('列表查询失败')
        })
    },
    copyQueryList (flag) {
      if (flag) {
        this.pageData.page = 1
      }
      let obj = {}
      obj['formName'] = this.queryForm['formName'] ? this.queryForm['formName'] : null
      obj['formTable'] = this.queryForm['formTable'] ? this.queryForm['formTable'] : null
      if (this.queryForm['formType']) {
        obj['formType'] = this.queryForm['formType']
      }

      let params = Object.assign(obj, {
        page: this.pageData.page - 1,
        size: 100000
      })
      this.$http
        .get('/api/lowcode/customize/cscpCustomizeVforms/getList', {
          params: params
        })
        .then((res) => {
          this.data = res.data.data
          this.tagetRow = this.data.filter(item => {
            return item.formId === this.moduleName
          })
          this.handleEdit(this.tagetRow[0])
        })
        .catch(() => {
          this.$Message.error('列表查询失败')
        })
    },
    cancel () {
      this.modal1 = false
      this.$refs['moduleRules'].resetFields()
    },
    handleDeleteMultiple: function () {
      let arr = this.selectedArr.map((item) => item.formId)
      if (arr.length < 1) {
        return this.$Message.error('删除失败,当前选择列表为空！')
      }
      this.$Modal.confirm({
        title: '警告',
        content: '<p>确定删除勾选的数据？</p>',
        onOk: () => {
          this.$http
            .delete('/api/lowcode/customize/cscpCustomizeVforms/delAll?formIds=' + arr)
            .then((res) => {
              this.$Message.success('删除成功')
              this.queryList()
              this.selectedArr = []
            })
            .catch((error) => {
              if (error.response) {
                this.$Message.error(
                  error.response.data.title
                    ? error.response.data.title
                    : '删除失败！'
                )
              }
            })
        },
        onCancel: () => {
        }
      })
    }
  },
}
</script>
<style lang="less">
.myTipContainer {
  .ivu-input {
    border-color: red;
  }
}
</style>
<style lang="less" scoped>
@import "~@/views/admin/styles/formStyle.less";

.modalHeaderClass {
  position: relative;
  color: #2d8cf0;
  font-size: 16px;
}

.normal {
  margin-right: 5px;
  color: #0056b5
}

.red {
  margin-right: 5px;
  color: red
}

</style>
